/**
 * 
 */
package com.gmail.blackdog1987.onedollar.web.controller;

import com.alipay.util.AlipayNotify;
import com.gmail.blackdog1987.onedollar.entity.TAlipayCallbackEntity;
import com.gmail.blackdog1987.onedollar.service.LuckyBagService;
import com.gmail.blackdog1987.onedollar.service.OrderService;
import com.gmail.blackdog1987.onedollar.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 
 * @author 董国超
 *
 */
@Controller
public class AlipayController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private LuckyBagService luckyBagService;
    /**
     * 订单支付
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="alipayPayOrderCallback", method=RequestMethod.POST)
    public String alipayPayOrderCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) {

        System.out.println("orange 回调的------alipayPayOrderCallback:::" + filter.toString());
        logger.info("orange 回调的------alipayPayOrderCallback:::" + filter.toString());

        if(!AlipayNotify.verify(filter))
        return "fail";
        boolean result = orderService.doAlipayPay(filter);
        return result?"sucess":"fail";
    }

    /**
     * 订单支付(一元/十元)
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="alipayPayOneDoloarCallback", method=RequestMethod.POST)
    public String alipayPayOneDoloarCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("orange 回调的------alipayPayOneDoloarCallback:::" + filter.toString());
        logger.info("orange 回调的------alipayPayOneDoloarCallback:::" + filter.toString());

        if(!AlipayNotify.verify(filter))
            return "fail";
        boolean result = orderService.doAlipayOneDollarPay(filter);
        return result?"sucess":"fail";
    }

    /**
     * 充值
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="chargeCallback", method=RequestMethod.POST)
    public String chargeCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) {
        logger.info("orange 回调的------chargeCallback:::" + filter.toString());
        System.out.println("orange 回调的------chargeCallback:::" + filter.toString());

        if(!AlipayNotify.verify(filter))
            return "fail";
        boolean result = userService.doCharge(filter);
        return result?"sucess":"fail";
    }

    /**
     * 发红包
     * 目前不支持单独红包一个一个支付，需要先充值
     * @param filter
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value="sendLuckyBagCallback", method=RequestMethod.POST)
    public String sendLuckyBagCallback(@RequestParam Map<String, String> filter, HttpServletRequest request, HttpServletResponse response) {
//        System.out.print(filter.toString());
        if(!AlipayNotify.verify(filter))
            return "fail";
        boolean result = luckyBagService.doAlipaySend(filter);
        return result?"sucess":"fail";
    }

    public static TAlipayCallbackEntity generateCallbackEntity(Map<String, String> filter) {
        String out_trade_no = filter.get("out_trade_no");		// json传递商品参数
        String subject = filter.get("subject");
        String payment_type = filter.get("payment_type");
        String notify_time = filter.get("notify_time");
        String notify_type = filter.get("notify_type");
        String notify_id = filter.get("notify_id");
        String trade_no = filter.get("trade_no");
        String trade_status = filter.get("trade_status");
        String buyer_id = filter.get("buyer_id");
        String buyer_email = filter.get("buyer_email");
        String total_fee = filter.get("total_fee");
        String quantity = filter.get("quantity");
        String price = filter.get("price");
        String body = filter.get("body");
        String gmt_create = filter.get("gmt_create");
        String gmt_payment = filter.get("gmt_payment");
        String is_total_fee_adjust = filter.get("is_total_fee_adjust");
        String use_coupon = filter.get("use_coupon");
        String discount = filter.get("discount");
        String refund_status = filter.get("refund_status");
        String gmt_refund = filter.get("gmt_refund");

        TAlipayCallbackEntity callbackEntity = new TAlipayCallbackEntity();
        callbackEntity.setOutTradeNo(out_trade_no);
        callbackEntity.setSubject(subject);
        callbackEntity.setPaymentType(payment_type);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if(notify_time!=null&&notify_time.length()!=0){

                    callbackEntity.setNotifyTime(new Timestamp(sdf.parse(notify_time).getTime()));
            }
            callbackEntity.setNotifyId(notify_type);
            callbackEntity.setNotifyId(notify_id);
            callbackEntity.setTradeNo(trade_no);
            callbackEntity.setTradeStatus(trade_status);
            callbackEntity.setBuyerId(buyer_id);
            callbackEntity.setBuyerEmail(buyer_email);
            if(total_fee!=null&&total_fee.length()!=0){
                callbackEntity.setTotalFee(new BigDecimal(total_fee));
            }
            if(quantity!=null&&quantity.length()!=0){
                callbackEntity.setQuantity(Integer.valueOf(quantity));
            }
            if(price!=null&&price.length()!=0){
                callbackEntity.setPrice(new BigDecimal(price));
            }
            callbackEntity.setBody(body);
            if(gmt_create!=null&&gmt_create.length()!=0){
                callbackEntity.setGmtCreate(new Timestamp(sdf.parse(gmt_create).getTime()));
            }
            if(gmt_payment!=null&&gmt_payment.length()!=0){
                callbackEntity.setGmtPayment(new Timestamp(sdf.parse(gmt_payment).getTime()));
            }
            callbackEntity.setIsTotalFeeAdjust(is_total_fee_adjust);
            callbackEntity.setUseCoupon(use_coupon);
            callbackEntity.setDiscount(discount);
            callbackEntity.setRefundStatus(refund_status);
            if(gmt_refund!=null&&gmt_refund.length()!=0){
                callbackEntity.setGmtRefund(new Timestamp(sdf.parse(gmt_refund).getTime()));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return callbackEntity;
    }

    @Override
    protected Map<String, Object> decorateResult(Map<String, Object> result) {
        return null;
    }
}
